﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Timers;
using BaseSniffer;

namespace ChromeSupport
{
    [Export(typeof(IBrowserSniffer))]
    public class ChromeSniffer : IBrowserSniffer
    {
       private string _activeTabName;
        public Timer Stopwatch { get; private set; }
        public event AlarmEventHandler TabChangeEvent;
            
        String Activetab{
            get { return _activeTabName; }
            set
            {
                if (value != _activeTabName)
                    if (TabChangeEvent != null)
                        TabChangeEvent(this, new TabChangeEventArgs(0, value));
                _activeTabName = value;
            }
        }

        public string ProcessName
        {
            get { return "chrome"; }
        }

        public ChromeSniffer()
        {
            Stopwatch = new Timer();

        }
        public bool GetFilter(String pBrowserName)
        {
            return pBrowserName.Equals(ProcessName);
        }

        public void StopSniff()
        {
            Stopwatch.Stop();
        }

        public void StartSniff()
        {
            Sniff(null, null);//TODO: is it the best way to do forst read of tab?
            Stopwatch.Start();
            Stopwatch.Interval = 1000;
            Stopwatch.Enabled = true;
            Stopwatch.Elapsed += new ElapsedEventHandler(Sniff);
                
        }

        private void Sniff(object sender, ElapsedEventArgs e)
        {
            foreach (Process process in Process.GetProcessesByName(ProcessName))
                if (PageAnalyzer.ActivePageProcess(process))
                    Activetab = process.MainWindowTitle;
        }
    }
}
